var express = require('express');
var app = express();
var formidable = require('formidable');
var db = require('./model/db.js');
var session = require('express-session');
var path = require('path');
var sd = require('silly-datetime');
var fs = require('fs');
var shangping = require('./model/shangping');
var url = require("url");
app.set("view engine", "ejs");
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}));
app.use(express.static('./public'));
app.use(express.static('./qpload'));

app.use('/login', function(req, res){
    res.render('login');
});
app.use('/zhuce',function(req, res){
    res.render('zhuce');
});
//处理后台商品添加请求
app.post('/admin',function(req, res){

    var form = new formidable.IncomingForm();
    form.uploadDir = path.normalize(__dirname + "/../" + "dianzishangwu" + "/"+"temp");
    form.parse(req,function(err, fields, files, next){
        if(err) {
            console.log("请求错误");
            next(); //这个中间件不受理这个请求了。
            return;
        }
        //获取改名路径
        var oldpath = files.img.path;
        //生成时间戳
        var ttt = sd.format(new Date(), 'YYYYMMDDHHmmss');
        var ran = parseInt(Math.random() * 89999 + 10000);
        var extname = path.extname(files.img.name);
        var newpath = path.normalize(__dirname + "/../dianzishangwu/qpload/"+ ttt + ran + extname);
        var src = ttt + ran + extname;
        fs.rename(oldpath, newpath, function(err){
            if(err) {
                throw err;
            }else {
                db.insertOne('shangping',{
                    "spName" : fields.spName,
                    "spMiaoshu" : fields.spMiaoshu,
                    "jiage" : fields.jiage,
                    "image" : newpath,
                    "src" : src
                },function(err, result){
                    res.json("提交成功");
                });
            }
        });
    });

});
app.post('/shanchu',function(req, res){
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        db.deleteMany('shangping',{"spName":fields.spName},function(err, result){
            res.send("1");
        })
    });

});
app.get('/chaxun',function(req, res){
    //解析中文编码
    var a = url.parse(req.url).query;
    var c = decodeURIComponent(a);
    var test = c.split('=')[1];
       db.find('shangping',{"spName":test},{},function(err, result){
           if(err){
               throw err;
               return;
           }else{
               res.send(result);
           }
       })

});
app.post('/updata',function(req, res){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files){

        var oldpath = files.img_1.path;
        //生成时间戳
        var ttt = sd.format(new Date(), 'YYYYMMDDHHmmss');
        var ran = parseInt(Math.random() * 89999 + 10000);
        var extname = path.extname(files.img_1.name);
        var newpath = path.normalize(__dirname+ "/../dianzishangwu/qpload/"+ ttt + ran + extname);
        var src = ttt + ran + extname;
        if(files.img_1.size == 0)
            newpath = fields.image_1;
        fs.rename(oldpath, newpath, function(err){
            if(err) {
                throw err;
            }else {
                db.updateMany('shangping',{
                    "spName" : fields.spName_2
                },{
                    $set: {
                        "spMiaoshu" : fields.spMiaoshu_1,
                        "jiage" : fields.biaojia,
                        "image" : newpath,
                        "src" : src
                        }
                },function(err, result){

                    if(err){

                        res.json("更新失败");
                        throw err;
                        return;
                    }else{
                        res.json("更新成功");
                    }
                })
            }
        });

    })
});

//购物车处理
app.post('/add',function (req, res) {
    var form = new formidable.IncomingForm();
    var UserName = req.session.UserName;
    if(UserName == "" || !UserName || UserName == 0 || UserName == null ){
        res.json("-1");
    }else{
        form.parse(req, function(err, fields){
            db.find('shangping',{
                "spMiaoshu":fields.spMiaoshu
            },{},function (err, result) {

                if(err) {
                    throw err;
                    return;
                }else{
                    var rest = result[0];
                    db.find('gouwuche',{
                        "UserName" : UserName,
                        "spMiaoshu" : result[0]
                    },{},function (err, result) {

                        var money = rest.jiage;
                        console.log(money);
                        if(!result || result == "" || result == 0 || result == null){

                            db.insertOne('gouwuche',{
                                "UserName" : UserName,
                                "spMiaoshu" : rest,
                                "count" : "1",
                                "money" : money
                            },function(err, result){
                                res.json("1");
                            })
                        }else{
                                db.updateMany('gouwuche',{
                                    "UserName" : UserName,
                                    "spMiaoshu" : result[0].spMiaoshu
                                },{
                                    $set:{
                                        "count" : (parseInt(result[0].count) + 1).toString(),
                                        "money" : ((parseInt(result[0].count) + 1) * parseInt(money)).toString()
                                    }
                                },function(){
                                    res.json("1");
                                })
                        }
                    });

                }
            })
        })
    }
});
//移除购物车
app.post('/yichu',function(req, res){
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields) {
        db.deleteMany('gouwuche',{
            "UserName" : fields.UserName,
            "spMiaoshu.spMiaoshu" : fields.spMiaoshu
        },function (err, result) {
            res.redirect('/gouwuche');
        });
    })
});

app.use('/gouwuche',function(req, res){
    var UserName = req.session.UserName;
    if(UserName == null || UserName == 0 ||UserName == "" || !UserName){
        res.redirect("/");
    }else{
        db.find('gouwuche',{
            "UserName" : UserName
        },{},function(err, result){
            if(err) throw err;

            db.find('gouwuche',{},{},function (err, result) {
                var heji = 0;
                for(var i = 0; i< result.length; i++){
                    heji = heji + parseInt(result[i].money);
                    //console.log(heji);
                }
                res.render('gouwuche',{
                    "UserName" : UserName,
                    "st" : result,
                    "heji" : heji
                })
            });

        })
    }

});

app.use('/admin', function(req, res){
    res.render('admin');
});

//处理新用户注册请求
app.post('/tijiao',function(req, res, next){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields){
        //插入数据
        db.insertOne('user',{
            "UserName" : fields.UserName,
            "PassWord" : fields.PassWord,
            "telephone" : fields.telephone,
            "address" : fields.address
        },function(err, result){
            if(err){
                res.json("-1");
                return;
            }else {
                res.json("1");

            }
        })
    })
});
//处理用户登录请求
app.post('/log',function(req, res){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields){

        db.find('user',{
            "UserName": fields.UserName,
            "PassWord" : fields.PassWord
        },{},function(err, result){
            if(err){
                throw err;
                res.json("-1");
            }
            if(result[0].PassWord === fields.PassWord){
                req.session.UserName = fields.UserName;
                req.session.PassWord = fields.PassWord;
                res.json("1")
            }
        })
    })
});

//搜索框搜索
app.get('/serach',function (req, res) {
    var a = url.parse(req.url).query;
    var c = decodeURIComponent(a);
    var test = c.split('=')[1];
    console.log(test);
    db.find('shangping',{"spName":test},{},function (err, result) {

       if(result && result == 0 && result == ''){
           res.json("-1");
       }else{
          res.json(result);
       }

    });

});
//获取商城信息
app.get('/du', function(req, res){
    var page = parseInt(req.query.page);
    db.find('shangping', {}, {
        "pagemount" : 12,
        "page" : page
    }, function(err, result){
        if(err) throw err;
        res.json(result);
    })
});
app.get('/', function(req, res){
    var counts = 0;
    var UserName = req.session.UserName || "请登录";
    db.getAllCount('shangping',function (count) {
        counts = Math.ceil(count / 12);
    });
    db.find('shangping',{},{
        "pagemount": counts
    },function (err, result) {
        res.render('index',{
            "UserName" : UserName,
            "liebiao" : result,
            "pagemount" : counts
        });

    })
});
app.listen(3000);